// app.js
import Dialog from './miniprogram_npm/@vant/weapp/dialog/dialog';
import io from './utils/socket.io-mp';
import * as Storage from './utils/storage';
import subPub from './utils/subPub';
const $api = require('./request/api').API;
App({
  async onLaunch() {
    // 初始化事件总线
    this.eventBus = {
      events: {},

      // 注册事件
      on(event, handler) {
        if (!this.events[event]) {
          this.events[event] = [];
        }
        this.events[event].push(handler);
      },

      // 注销事件
      off(event, handler) {
        if (!this.events[event]) return;
        this.events[event] = this.events[event].filter(h => h !== handler);
      },

      // 触发事件
      emit(event, data) {
        if (!this.events[event]) return;
        this.events[event].forEach(handler => handler(data));
      }
    };

    //小程序版本更新
    this.autoUpdate();
    // 获取设备信息
    this.getSystemInfo();
    if (wx.getStorageSync(Storage.USER_ID)) {
      this.initSocket();
    }
    // 初始化，需要联网
    this.init();
  },
  // // 初始化存储信息
  async init() {
    // 监听网络的变化
    // wx.onNetworkStatusChange(res => {
    //   wx.showToast({
    //     title: res.isConnected,
    //   })
    //   console.log(res, "监听网络变化")
    // })
    // 判断有没有录音
    wx.getSetting({
      success: res => {
        if (res.authSetting.hasOwnProperty('scope.record')) {
          this.globalData.recordSound = res.authSetting['scope.record'];
        }
      }
    });
    await this.getOpenId();
  },
  initSocket() {
    let { socket } = this.globalData;
    if (!socket) {
      this.globalData.socket = io(require('./env').socketUrl);
      socket = this.globalData.socket;
    }
    socket.on('connect', () => {
      socket.emit('refresh', wx.getStorageSync(Storage.USER_ID));
      socket.on('message', ({ msg, source }) => {
        if (source === 99) {
          // msg = JSON.parse(msg);
          // Dialog.alert({ title: '提示', message: msg.content || '' }).then(() => {
          //   $api.updateRecordState({ sysNotifyId: msg.sysNotifyId });
          // });
        } else {
          const type = Number(source) - 30;
          if (type < 3 || type > 11) return;
          const pages = getCurrentPages();
          let page = '';
          page = pages.find(item => item.route == 'pages/equipment/index');
          page && page.getList();
          switch (type) {
            case 3: // 烟雾报警器报警
              Dialog.alert({ title: '提示', message: '烟雾报警器报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsY/index');
              page && page.getData();
              break;
            case 4: // 燃气报警器报警
              Dialog.alert({ title: '提示', message: '燃气报警器报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsR/index');
              page && page.getData();
              break;
            case 5: // 门磁报警器报警
              Dialog.alert({ title: '提示', message: '门磁报警器报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsM/index');
              page && page.getData();
              break;
            case 6: // 水浸卫士报警
              Dialog.alert({ title: '提示', message: '水浸卫士报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsW/index');
              page && page.getData();
              break;
            case 8: // 紧急呼叫器报警
              Dialog.alert({ title: '提示', message: '紧急呼叫器报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsS/index');
              page && page.getData();
              break;
            case 9: //  跌倒报警器报警
              Dialog.alert({ title: '提示', message: '跌倒报警器报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsD/index');
              page && page.getData();
              break;
            case 10: // 红外探测器报警
              Dialog.alert({ title: '提示', message: '红外探测器报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsH/index');
              page && page.getData();
              break;
            case 11: // 睡眠监测仪报警
              Dialog.alert({ title: '提示', message: '睡眠监测仪报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsL/index');
              page && page.getData();
              break;
            case 15: // 拐杖
              Dialog.alert({ title: '提示', message: '拐杖报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsSC/index');
              page && page.getData();
              break;
            case 16: // 胸牌
              Dialog.alert({ title: '提示', message: '胸牌报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsNB/index');
              page && page.getData();
              break;
            case 17: // 手表
              Dialog.alert({ title: '提示', message: '手表报警，请及时处理' });
              page = pages.find(item => item.route == 'subcontract/equipment/pages/detailsSW/index');
              page && page.getData();
              break;
          }
        }
      });
      socket.on('sleepSyncDetectionPush', data => {
        data = JSON.parse(data);
        console.log('睡眠监测数据', data);
        subPub.emit('sleepSyncDetectionPush', data);
      });
      socket.on('deviceOffline', data => {
        // data = JSON.parse(data)
        console.log('睡眠监测仪离线');
        subPub.emit('deviceOffline', data);
      });
      socket.on('deviceOnline', data => {
        // data = JSON.parse(data)
        console.log('睡眠监测仪在线');
        subPub.emit('deviceOnline', data);
      });
    });
    socket.on('disconnect', () => {
      console.log('断开连接');
      setTimeout(() => {
        this.initSocket();
      }, 2000);
    });
  },
  //通过code获取openId,这个函数也可以返回openId
  getOpenId() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: async res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            this.globalData.userCode = res.code;
            res = await $api.getOpenId({ code: res.code, appId: Storage.APPID });
            let openId = res.data.data;
            wx.setStorageSync(Storage.USER_OPEN_ID, openId);
            resolve(openId);
            // 存储openId
            // 因为获取到openId是异步的，但是后面扫码操作需要同步获取openId，后面要获取openId的的地方必须写一个回调函数，这里执行这个回调函数
            if (this.openIdCallback) {
              this.openIdCallback(openId);
            }
          }
        }
      });
    });
  },
  /**
   * 登录逻辑写在这里，其它页面也可以调用,首先会判断是否登录，如果已经登录且传进去回调函数就会执行那个回调函数
   * @param {function} callback 登录后的回调函数
   * @param {object} loginOptin 登录参数,不写有默认的
   */
  async isLogin(callBack, loginOption = {}) {
    const openId = wx.getStorageSync(Storage.USER_OPEN_ID);

    if (!openId) {
      // 不存在openId那么就先获取openId再登录
      this.openIdCallback = openId => {
        if (openId) {
          this.isLogin(callBack);
        }
      };
      return;
    }
    if (wx.getStorageSync(Storage.ACCESS_TOKEN)) {
      // 已经登录就直接执行回调函数
      callBack();
      return;
    }
    this.login(callBack, loginOption);
    // // 没有登录就先获取openId
    // let params = Object.assign({
    //   openId,
    //   loginType: 20,
    //   userRole: 2,
    //   appId: Storage.APPID,
    // }, loginOption);
    // const res = await $api.userLogin(params)
    // const { userCode, userRole, detailRole, imageUrl, nickName, userId, level, phone, casUserId } = res.data.data
    // // 详细角色区分专属商户
    // wx.setStorageSync(Storage.ACCESS_TOKEN, userCode)
    // wx.setStorageSync(Storage.USER_ROLE, userRole)
    // wx.setStorageSync(Storage.USER_ID, userId)
    // wx.setStorageSync(Storage.DETAIL_ROLE, detailRole)
    // wx.setStorageSync(Storage.LEVEL, level)
    // wx.setStorageSync(Storage.PHONE, phone)
    // wx.setStorageSync(Storage.AVATAR_URL, imageUrl)
    // wx.setStorageSync(Storage.NICK_NAME, nickName)
    // wx.setStorageSync(Storage.CAS_USER_ID, casUserId)
    // // 执行socket
    // const { socket } = this.globalData
    // if (socket) {
    //   socket.removeAllListeners()
    //   console.log("移除所有的监听")
    // }
    // subPub.cbArr.length && subPub.clear()  // 清除全局的监听
    // this.initSocket()
    // callBack()
  },
  async login(callBack, loginOption = {}) {
    const openId = wx.getStorageSync(Storage.USER_OPEN_ID);
    let params = Object.assign(
      {
        openId,
        loginType: 20,
        userRole: 2,
        appId: Storage.APPID
      },
      loginOption
    );
    const res = await $api.userLogin(params);
    const { userCode, userRole, detailRole, imageUrl, nickName, userId, level, phone, casUserId } = res.data.data;
    // 详细角色区分专属商户
    wx.setStorageSync(Storage.ACCESS_TOKEN, userCode);
    wx.setStorageSync(Storage.USER_ROLE, userRole);
    wx.setStorageSync(Storage.USER_ID, userId);
    wx.setStorageSync(Storage.DETAIL_ROLE, detailRole);
    wx.setStorageSync(Storage.LEVEL, level);
    wx.setStorageSync(Storage.PHONE, phone);
    wx.setStorageSync(Storage.AVATAR_URL, imageUrl);
    wx.setStorageSync(Storage.NICK_NAME, nickName);
    wx.setStorageSync(Storage.CAS_USER_ID, casUserId);
    // 执行socket
    const { socket } = this.globalData;
    if (socket) {
      socket.removeAllListeners();
      console.log('移除所有的监听');
    }
    subPub.cbArr.length && subPub.clear(); // 清除全局的监听
    this.initSocket();
    callBack();
  },

  /**
   * 小程序版本自动更新
   */
  autoUpdate: function () {
    /**
     * 获取版本号，判断是否与当前版本号是否一致如果不一致就代表新的版本发布了，
     * 新的版本发布需要删除本地存储，有时候微信或者许久没有使用小程序就会未启动同步更新，wx.getUpdateManager不会监听得到
     */
    const { miniProgram } = wx.getAccountInfoSync();
    const { version } = miniProgram;
    const localVersion = wx.getStorageSync(Storage.VERSION);
    if (localVersion != version) {
      // 版本号不一样表示小程序已经更新，清除缓存，如果不是硬要清除缓存就不需这段代码
      const openId = wx.getStorageSync(Storage.USER_OPEN_ID);
      wx.clearStorageSync();
      if (openId) wx.setStorageSync(Storage.USER_OPEN_ID, openId);
    }
    wx.setStorageSync(Storage.VERSION, version);
    // const that = this;
    //获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      //获取全局唯一的版本更新管理器，用于管理小程序更新
      const updateManager = wx.getUpdateManager();
      //1.检查小程序是否有新版本发布
      updateManager.onCheckForUpdate(function (res) {
        //请求完新版本信息的回调
        if (res.hasUpdate) {
          console.log('监听到更新', res.hasUpdate);
          //2.小程序有新版本，则静默下载新版本，做好更新准备
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好,是否重启应用?',
              success: function (res) {
                if (res.confirm) {
                  //3.新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  // 新的版本需要清除token重新登录，但是需要保存openId
                  const openId = wx.getStorageSync(Storage.USER_OPEN_ID);
                  wx.clearStorageSync();
                  if (openId) wx.setStorageSync(Storage.USER_OPEN_ID, openId);
                  updateManager.applyUpdate();
                } else if (res.cancel) {
                  //如果需要强制更新，则给出二次弹窗；如果不需要，则这里的代码都可以删除
                  wx.showModal({
                    title: '温馨提示~',
                    content: '本次版本更新涉及到新的功能添加,旧版本无法正常访问哦',
                    success: function (resc) {
                      if (resc.confirm) {
                        updateManager.applyUpdate();
                        //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        // updateManager.applyUpdate()
                      }
                    }
                  });
                }
              }
            });
          });
          updateManager.onUpdateFailed(function () {
            //新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
            });
          });
        }
      });
    } else {
      //如果希望用户在最新版本的用户端上体验您的小程序，可以这样提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试'
      });
    }
  },

  // 设置tabbar
  editTabBar: function () {
    //使用getCurrentPages可以获取当前加载中所有的页面对象的一个数组，数组最后一个就是当前页面。
    var curPageArr = getCurrentPages(); //获取加载的页面
    var curPage = curPageArr[curPageArr.length - 1]; //获取当前页面的对象
    var pagePath = curPage.route; //当前页面url
    if (pagePath.indexOf('/') != 0) {
      pagePath = '/' + pagePath;
    }

    var tabBar = this.globalData.tabBar;
    for (var i = 0; i < tabBar.list.length; i++) {
      tabBar.list[i].active = false;
      if (tabBar.list[i].pagePath == pagePath) {
        tabBar.list[i].active = true; //根据页面地址设置当前页面状态
      }
    }
    curPage.setData({
      tabBar: tabBar
    });
  },
  // 获取设备信息
  getSystemInfo() {
    let menuBtn = wx.getMenuButtonBoundingClientRect();
    let res = wx.getSystemInfoSync();
    console.log('设备信息', res);
    this.globalData.menuBtnTop = menuBtn.top;
    this.globalData.menuBtnBottom = menuBtn.bottom;
    this.globalData.menuBtnLeft = menuBtn.left;
    this.globalData.menuBtnRight = menuBtn.right;
    this.globalData.menuBtnHeight = menuBtn.height;
    this.globalData.menuBtnWidth = menuBtn.width;
    this.globalData.bottomHeight = res.screenHeight - res.safeArea.height;
    this.globalData.screenHeight = res.screenHeight;
    this.globalData.systemInfo = res;
  },
  globalData: {
    userInfo: null,
    userCode: '',
    serviceList: [],
    oldServiceMsg: [],
    menuBtnTop: '', //设备顶部到胶囊的距离,
    menuBtnHeight: '', //右上角胶囊的高度,
    menuBtnBottom: '',
    menuBtnLeft: '',
    menuBtnRight: '',
    bottomHeight: 0, //iphone底部黑色条高度
    screenHeight: '',
    systemInfo: null,
    socket: null,
    miniProgramAccountInfo: null
  }
});
